package com.noahplat.sms.filter;

import com.noahplat.common.cusexception.RedisException;
import com.noahplat.common.utils.NoahEnum;
import com.noahplat.common.utils.RedisUtils;
import com.noahplat.sms.mapper.WhiteipMapper;
import com.noahplat.sms.pojo.Whiteip;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;

@Component
public class IpFilter implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private WhiteipMapper whiteipMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        boolean key = redisUtils.hasKey(NoahEnum.WHITEIPDIR.getCode()+request.getRemoteAddr());
        if(!key){
            int number = 0;
            Example example = new Example(Whiteip.class);
            example.createCriteria().orEqualTo("whiteip",request.getRemoteAddr());
            Whiteip whiteip = whiteipMapper.selectOneByExample(example);
            if(ObjectUtils.isEmpty(whiteip)){
                Object object = redisUtils.get(NoahEnum.IPDIR.getCode()+request.getRemoteAddr());
                if(!ObjectUtils.isEmpty(object)){
                    number = Integer.parseInt(object.toString());
                }
                if(number > 100){
                    return false;
                }
                number++;
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,24);
                calendar.set(Calendar.SECOND,0);
                calendar.set(Calendar.MINUTE,0);
                calendar.set(Calendar.MILLISECOND,0);
                long time = calendar.getTimeInMillis()/1000;
                long nowtime = System.currentTimeMillis()/1000;
                long date = time - nowtime;
                if(date == 0){
                    date = 86400;
                }
                boolean res = redisUtils.set(NoahEnum.IPDIR.getCode()+request.getRemoteAddr(),String.valueOf(number),date);
            }else{
                boolean res = redisUtils.lSet(NoahEnum.WHITEIPDIR.getCode()+request.getRemoteAddr(),whiteip);
            }
        }
        return true;
    }
}
